package com.asurplus.api.controller;

import com.asurplus.common.minio.MinioConst;
import com.asurplus.common.minio.MinioUtils;
import com.asurplus.common.utils.R;
import com.asurplus.system.entity.SysFiles;
import com.asurplus.system.service.SysFilesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 附件管理
 *
 * @Author admin
 **/
@Slf4j
@Api(tags = "附件管理")
@RestController
@RequestMapping("/api/files")
public class FilesApiController {

    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private SysFilesService sysFilesService;

    @ApiOperation(value = "上传附件")
    @PostMapping(value = "upload", headers = "content-type=multipart/form-data")
    public R uploadFile(HttpServletRequest request) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multiRequest.getFile("file");
        return minioUtils.uploadFile(file, "app");
    }

    @ApiOperation(value = "预览附件")
    @GetMapping(value = "view/{id}")
    public void view(@PathVariable Integer id, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            SysFiles sysFiles = sysFilesService.getById(id);
            // 文件和文件路径不能为空
            if (sysFiles != null && !StringUtils.isBlank(sysFiles.getUrl()) && minioUtils.isPicture(sysFiles.getSuffix())) {
                response.setContentType("image/jpeg;charset=utf-8");
                InputStream imgIn = minioUtils.getObject(MinioConst.MINIO_BUCKET, sysFiles.getUrl());
                if (imgIn != null) {
                    inputStream = new BufferedInputStream(imgIn);
                    outputStream = response.getOutputStream();
                    byte[] buf = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, length);
                    }
                    response.flushBuffer();
                }
            }
        } catch (IOException e) {
            log.error("预览图片失败" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @ApiOperation(value = "下载附件")
    @GetMapping(value = "download/{id}")
    public void download(@PathVariable Integer id, HttpServletResponse response) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            SysFiles sysFiles = sysFilesService.getById(id);
            if (sysFiles != null) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(sysFiles.getName().getBytes("UTF-8"), "iso-8859-1"));
                InputStream imgIn = minioUtils.getObject(MinioConst.MINIO_BUCKET, sysFiles.getUrl());
                // 文件和文件路径不能为空
                if (imgIn != null && !StringUtils.isBlank(sysFiles.getUrl())) {
                    inputStream = new BufferedInputStream(imgIn);
                    outputStream = response.getOutputStream();
                    byte[] buf = new byte[1024];
                    int length;
                    while ((length = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, length);
                    }
                    response.flushBuffer();
                } else {
                    response.setStatus(404);
                }
            }
        } catch (Exception e) {
            log.info("文件下载失败" + e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != outputStream) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
